#include "thread.h"
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include "reactor.h"
void Thread::ClientIoEventCallBack(int fd,short events,void* arg)
{
    char buf[LARGE_BUF_LEN]={0};
    if(read(fd,buf,LARGE_BUF_LEN)<=0)
    {
        LOG_INFO<<"client disconneted!";
    }
    LOG_INFO<<buf;
    
}
void Thread::SocketPairEventCallBack(int fd,short events,void* arg)
{
    Thread* thread=static_cast<Thread*>(arg);
    int cfd=0;
    if(read(fd,&cfd,4<=0))
    {
        LOG_ERROR<<strerror(errno);
    }
    thread->m_reactor->AddEventAndHander(cfd,EV_READ|EV_PERSIST,Thread::ClientIoEventCallBack,arg);
}
void* Thread::taskFunc(void* arg)
{
    Thread* thread=static_cast<Thread*>(arg);
    thread->m_reactor=new Reactor();
    thread->m_reactor->AddEventAndHander(thread->GetSocketPairSecond(),EV_READ|EV_PERSIST,Thread::SocketPairEventCallBack,arg);
    LOG_INFO<<thread->GetTid();
    thread->m_reactor->Loop();
    return NULL;
}
Thread::Thread()
{
    if(pthread_create(&m_tid,NULL,taskFunc,this))
    {
        LOG_ERROR<<"creat thread faild!";
    }
    if(-1==socketpair(AF_UNIX,SOCK_STREAM,0,m_channle))
    {
        LOG_ERROR<<strerror(errno);
    }
}
Thread::~Thread()
{
    pthread_join(m_tid,NULL);
}

int Thread::GetSocketPairFirst()const
{
    return m_channle[0];
}
int Thread::GetSocketPairSecond()const
{
    return m_channle[1];
}
pthread_t Thread::GetTid()const
{
    return m_tid;
}
